package com.study.testSpringBoot.interceptor;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.study.testSpringBoot.interceptor.anno.CheckParams;

//@Component
public class TestInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//判断拦截的是否方法
		if(!(handler instanceof HandlerMethod)) {
			
			return true;
		}
		//获取方法上的注解
		CheckParams params = ((HandlerMethod) handler).getMethodAnnotation(CheckParams.class);
		//使用了注解，并且参数值为true
		if(params != null) {
			System.out.println("用到注解了。。。" + params.isNull());
			if(params.isNull()) {
				//该方法获取不到参数
				MethodParameter[] parameters = ((HandlerMethod) handler).getMethodParameters();
//				Map<String, String[]> map = request.getParameterMap();
				Enumeration<String> names = request.getParameterNames();
//				String string = names.nextElement();
//				HandlerMethod method = ((HandlerMethod) handler).getResolvedFromHandlerMethod();
//				MethodParameter returnType = ((HandlerMethod) handler).getReturnType();
//				String shortLogMessage = ((HandlerMethod) handler).getShortLogMessage();
				
				//这种验证方式不能将参数放在body里面
				while (names.hasMoreElements()) {
					//获取参数值
					String value = request.getParameter(names.nextElement());
					if(value != null && !"".equals(value)) {
						System.out.println(value);
					}else {
						throw new NullPointerException("参数值不能为空！");
					}
				}
//				if(parameters != null && parameters.length > 0) {
//					for(MethodParameter p : parameters) {
//						//获取参数名
//						String paramName = p.getParameterName();
//						//获取参数值
//						String value = request.getParameter(paramName);
//						if(value != null && !"".equals(value)) {
//							System.out.println(value);
//						}else {
//							throw new RuntimeException("参数值不能为空！");
//						}
//					}
//				}
			}
		}
		
        return true;
	}
	
//	@Override
//	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
//			ModelAndView modelAndView) throws Exception {
//		System.out.println("postHandle...");
//		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//	}
//	
//	@Override
//	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
//			throws Exception {
//		System.out.println("afterCompletion...");
//		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//	}
}
